package ar.com.ford.it.fullEconomics.interfaces;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.WorkerFileFacade;
import ar.com.ford.it.fullEconomics.logic.WorkerFileLogic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx01Intfsource;
import com.ford.it.ftp.FtpClientAttributes;
import com.ford.it.ftp.FtpProxyClient;
import com.ford.it.ftp.FtpProxyException;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.properties.PropertyException;
import com.ford.it.properties.PropertyGroup;
import com.ford.it.properties.PropertyManager;
import com.ford.it.properties.PropertyResourceException;

public class WorkerReadFile {
	
	private static final String CLASS_NAME = WorkerFileLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);
	
	private String userFtp;
	private String passFtp;
	private String hostFtp;
	
	private String contentType[] = {"T","B"};	

	public WorkerReadFile(){
		try {			
			
			this.contextInitialized();
			
		}  catch (PropertyResourceException e) {            
            e.printStackTrace();
        } catch (PropertyException e) {
            e.printStackTrace();
        }
	}
	
	/**
     * Find and Download file from ftp to Field Blob
     * 
     * @param FullEconomicsWslxUser
     * @param user
     * @throws FullEconomicsException
     */
	public void downloadFileFromFtptoBlob()	
	{
		
		InputStream input;
		boolean isFileExists;
		
		WorkerFileFacade facade = new WorkerFileFacade();
		
		try{
			FtpClientAttributes ftpAttribs = new FtpClientAttributes.Builder(hostFtp, userFtp, passFtp).timeout(99999).build();
			System.out.println("xxxx es:" + passFtp);
			FtpProxyClient ftpClient = new FtpProxyClient(ftpAttribs);
			
			
			
			Iterator it= this.getNameFileDB().iterator();
			while(it.hasNext()){
				Teesx01Intfsource intfsource =(Teesx01Intfsource) it.next ();
				System.out.println("NAME-->> " + intfsource.getEesx01IntfNameN() + "--" + intfsource.getEesx01IntfTypeCodeC());
				
				try {
					
					try {
				
					   isFileExists = isExisteFile(ftpClient, intfsource.getEesx01IntfNameN());
					}
					catch (Exception e) {
						e.printStackTrace();
						isFileExists = false;
					}
					if(isFileExists){
						if(intfsource.getEesx01IntfTypeCodeC().equalsIgnoreCase(contentType[0])){
							ftpClient.setAsciiMode();
						}else{
							ftpClient.setBinaryMode();
						}
						
						/* ######### DOWNLOAD ######### */
						input = ftpClient.getFile(intfsource.getEesx01IntfNameN());			
						
						int bufferSize  = 1024;
						int bytesread=0;
								
						ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);
								
						byte[] buffer= new byte[bufferSize];
						
						while(true){ 
							bytesread = input.read(buffer);				
							if (bytesread == -1){
								break;
							}				
							baos.write(buffer,0,bytesread); 				
						}
						
						byte file[] = baos.toByteArray();
						int size = file.length;
						
						try{
							facade.createFileConten(intfsource, file, size);
						}catch(FullEconomicsException e){
							e.printStackTrace();
						}
						
						input.close();
						baos.close();
						
					}//end if existe file
					else { // LSPARACI: agregado para que grabe aunque no este el archivo presente
						try{
							facade.createFileConten(intfsource, null, 0);
						}catch(FullEconomicsException e){
							e.printStackTrace();
						}
					}
				} 
				catch (Exception e){
					System.out.println("FTP Error");
					e.printStackTrace();
				}
			}//end while list name file
			
			ftpClient.cleanup();
			
		}catch (Exception e) {
			e.printStackTrace();
		}	      
    	 	
	}	
	
	private boolean isExisteFile(FtpProxyClient ftpClient, String file){
		boolean isExisteFile = false;
		try{
			isExisteFile = ftpClient.isFileExists(file);
			isExisteFile = true;
		}catch(FtpProxyException fpe){
			System.out.println("Archivo " + file + " inexistente");
		}
		catch(Exception e){
			e.printStackTrace();			
		}
		return isExisteFile;
	}
	
	private Collection <Teesx01Intfsource> getNameFileDB(){
		String METHOD_NAME = "getNameFileDB";
        log.entering(CLASS_NAME, METHOD_NAME);
        
        Collection<Teesx01Intfsource> Intfsource = null;
		/* get TEESX01_INTFSOURCE */
		try{
			WorkerFileFacade facade = new WorkerFileFacade();			 
			Intfsource = facade.findIntfSourceByFlag(contentType);			
		}catch (FullEconomicsException e) {
			e.printStackTrace();            
		}
		
		return Intfsource;
	}
	
	private void contextInitialized () throws PropertyResourceException {
	    PropertyManager pm = PropertyManager.getInstance();
	    try {
	        // First step is to initialize the framework 
	        pm.initDynaProp();
	       // Do a one-time load all app-specific property-group  
	       // namespaces here to be used during run-time.
	        pm.loadFromDB("ftpconnection_fullee");
	        PropertyGroup pg = (PropertyGroup) pm.getGroup("ftpconnection_fullee");
    
	        this.userFtp = pg.getString("User");
	        this.passFtp = pg.getString("Password");
	        this.hostFtp = pg.getString("Host");
	        
	    } catch (PropertyResourceException pre) {
	        // DynaProp and/or application could not be initialized!
	        throw pre;
	    }
	}

}
